import React, { useRef, useState } from 'react';
import { router, Text, Image, View, ScrollView, publishDps, Button, showToast } from '@ray-js/ray';
import { Card } from '@/components/card';
import { IconFont, Empty } from '@/components';
import Strings from '@/i18n';
import {
  CellGroup,
  Cell,
  Switch,
  SwipeCell,
  ActionSheet,
  DateTimePicker,
  Picker,
} from '@ray-js/smart-ui';
import { useDevice, useProps } from '@ray-js/panel-sdk';
import { useAppConfig } from '@/hooks/useAppConfig';
import { NavBarCustom } from '@/components/NavBarCustom';
import res from '@/res/image';
import { getCachedSystemInfo } from '@/api/getCachedSystemInfo';

import { decodeDisinfect, encodeDisinfect } from '@/utils/parse';
import styles from './index.module.less';

import { useStaticsRange } from '../curve/hooks/useStatRange';
import clsx from 'clsx';

const { safeArea } = getCachedSystemInfo();

const { height } = safeArea;

const max = 10;

const initValue = {
  hour: 0,
  minute: 0,
  duration: 0,
  status: true,
};

const getTimeMeasureUtils = (time: {
  hour: number;
  minute: number;
  duration: number;
  status: boolean;
}) => {
  if (time.hour === undefined) {
    return '';
  }

  const { hour, minute } = time;

  return `${hour < 10 ? `0${hour}` : hour}:${minute < 10 ? `0${minute}` : minute}`;
};

const getDurationMeasureUtils = (
  time: {
    hour: number;
    minute: number;
    duration: number;
    status: boolean;
  } | null
) => {
  if (time.duration === undefined) {
    return '';
  }

  const { duration } = time;

  return `${duration}min`;
};

const columns = new Array(100).fill(0).map((_, index) => `${index + 1}`);

export function SterillizationSchedule() {
  const [delShow, setDelShow] = useState(false);

  const [addShow, setAddShow] = useState(false);

  const [addState, setAddState] = useState<'list' | 'schedule' | 'uv'>('list');

  const {
    uv_onoff_time: uvOnOffTime, // 杀菌
  } = useProps();

  const uvlist = decodeDisinfect(uvOnOffTime);

  const currentRef = useRef<number>(0);

  const [addTime, setAddTime] = useState({} as any);

  const startTimeRef = useRef({
    hour: 12,
    minute: 0,
  });

  const durationRef = useRef(1);

  // const
  return (
    <View className={styles.view}>
      <NavBarCustom name={Strings.getLang('sterillizationSchedule')} back />
      <View className={styles.pageTips}>
        <Text>{Strings.getLang('sterillizationTips')}</Text>
      </View>
      <ScrollView
        className={styles.scrollView}
        scrollY
        refresherTriggered
        style={{
          height: `calc(${height}px - env(safe-area-inset-bottom) - env(safe-area-inset-top) - 100rpx)`,
        }}
      >
        <View className={styles.cellGroup}>
          {uvlist.map((item, index) => (
            <View
              key={index}
              className={styles.item}
              onLongPress={() => {
                currentRef.current = index;
                setDelShow(true);
              }}
            >
              <View className={styles.time}>
                <Text className={styles.timeText}>{`${
                  item.hour < 10 ? `0${item.hour}` : item.hour
                }:${item.minute < 10 ? `0${item.minute}` : item.minute}`}</Text>
                <Text className={styles.durationText}>{`${item.duration}min`}</Text>
              </View>
              <Switch
                checked={item.status}
                onChange={v => {
                  const str = encodeDisinfect(
                    uvlist.map((item, i) => ({
                      ...item,
                      status: i === index ? !item.status : item.status,
                    }))
                  );

                  publishDps({
                    uv_onoff_time: str,
                  });
                }}
              />
            </View>
          ))}
        </View>
      </ScrollView>

      <View className={styles.addButtonBox}>
        <Button
          className={clsx(styles.addButton, uvlist.length >= max && styles.disabledBtn)}
          disabled={uvlist.length >= max}
          onClick={() => {
            setAddShow(true);
            durationRef.current = 1;
            startTimeRef.current = {
              hour: 12,
              minute: 0,
            };
          }}
        >
          {Strings.getLang('add')}
        </Button>
      </View>

      <ActionSheet show={delShow} onCancel={() => setDelShow(false)}>
        <View className={styles.content}>
          <View className={styles.titleText}>
            <Text>{Strings.getLang('sterillizationSchedule')}</Text>
          </View>
          <View className={styles.tipsText}>
            <Text>{Strings.getLang('sterillizationScheduleDelTips')}</Text>
          </View>

          <View className={styles.buttonGroup}>
            <Button className={styles.button} onClick={() => setDelShow(false)}>
              {Strings.getLang('cancel')}
            </Button>
            <Button
              className={styles.button}
              onClick={() => {
                // uvlist[currentRef.current].status = false;
                // uvlist[currentRef.current].status = false;
                const newList = uvlist.filter((item, index) => index !== currentRef.current);
                const str = encodeDisinfect(newList);

                publishDps({
                  uv_onoff_time: str,
                });

                setDelShow(false);
              }}
            >
              {Strings.getLang('confirm')}
            </Button>
          </View>
        </View>
      </ActionSheet>
      <ActionSheet show={addShow} onCancel={() => setAddShow(false)}>
        {addState === 'list' ? (
          <View className={styles.content}>
            <View className={styles.titleText}>
              <Text>{Strings.getLang('sterillizationSchedule')}</Text>
            </View>
            <View className={styles.setGroup}>
              <Cell
                title={Strings.getLang('sterillizationScheduleTime')}
                isLink
                value={getTimeMeasureUtils(addTime)}
                titleStyle={{
                  fontWeight: 700,
                }}
                valueClass={styles.valueText}
                onClick={() => setAddState('schedule')}
              />
              <Cell
                title={Strings.getLang('sterillizationUVTime')}
                isLink
                value={getDurationMeasureUtils(addTime)}
                titleStyle={{
                  fontWeight: 700,
                }}
                valueClass={styles.valueText}
                onClick={() => setAddState('uv')}
              />
            </View>
            <View className={styles.buttonGroup}>
              <Button className={styles.button} onClick={() => setDelShow(false)}>
                {Strings.getLang('cancel')}
              </Button>
              <Button
                className={styles.button}
                disabled={
                  addTime.hour === undefined ||
                  addTime.minute === undefined ||
                  addTime.duration === undefined
                }
                onClick={() => {
                  if (
                    addTime.hour === undefined ||
                    addTime.minute === undefined ||
                    addTime.duration === undefined
                  ) {
                    return;
                  }
                  if (
                    uvlist.find(
                      item => item.hour === addTime.hour && item.minute === addTime.minute
                    )
                  ) {
                    setAddShow(false);
                    setTimeout(() => {
                      showToast({
                        title: Strings.getLang('sterillizationScheduleAddSameTimeTips'),
                        icon: 'error',
                      });
                    }, 10);
                    return;
                  }

                  const newList = [
                    ...uvlist,
                    {
                      ...addTime,
                    },
                  ];
                  const str = encodeDisinfect(newList);

                  publishDps({
                    uv_onoff_time: str,
                  });

                  setAddShow(false);
                }}
              >
                {Strings.getLang('confirm')}
              </Button>
            </View>
          </View>
        ) : (
          <View className={styles.content}>
            <View className={styles.editTitle}>
              {Strings.getLang(addState === 'schedule' ? 'startTimeTitle' : 'uvtitle')}
            </View>
            <View className={styles.pickerBox}>
              {addState === 'schedule' ? (
                <View className={styles.timePickerBox}>
                  <DateTimePicker
                    type="time"
                    value="12:00"
                    showToolbar={false}
                    onInput={v => {
                      const hour = (v.detail as string).split(':')[0];
                      const minute = (v.detail as string).split(':')[1];
                      startTimeRef.current = {
                        hour: Number(hour),
                        minute: Number(minute),
                      };
                    }}
                    locale={{
                      hour: Strings.getLang('hour'),
                      minute: Strings.getLang('minute'),
                    }}
                  />
                </View>
              ) : (
                <View className={styles.timePickerBox}>
                  <Picker
                    columns={columns}
                    onChange={v => {
                      durationRef.current = Number(v.detail.value);
                    }}
                    unit={Strings.getLang('minute')}
                  />
                </View>
              )}
            </View>
            <View className={styles.buttonGroup}>
              <Button className={styles.button} onClick={() => setAddShow(false)}>
                {Strings.getLang('cancel')}
              </Button>
              <Button
                className={styles.button}
                onClick={() => {
                  if (addState === 'schedule') {
                    setAddTime(x => ({
                      ...x,
                      ...startTimeRef.current,
                    }));
                    setAddState('list');
                  }

                  if (addState === 'uv') {
                    setAddTime(x => ({
                      ...x,
                      duration: Number(durationRef.current),
                    }));
                    setAddState('list');
                  }
                }}
              >
                {Strings.getLang('confirm')}
              </Button>
            </View>
          </View>
        )}
      </ActionSheet>
    </View>
  );
}

export default SterillizationSchedule;
